
$(document).ready(() => {
  if ($('x-guanlian .main_table').css('display') === 'none') {
    $('#add_new_guanlian_table').one('click', (evt) => {
      $('x-guanlian .placeholder').remove()
      $('x-guanlian .main_table').css('display', 'block')
    })
  } else {
    $('#add_new_guanlian_table').remove()
  }

  // 添加关联 按钮
  $('#add_new_guanlian').on({click: addNewGuanlian}, {})
  $('x-guanlian .btn_modifiy').each((index, item) => {
    $(item).on({click: modifyThisLine}, {})
  })
  // 转义关联理由
  // $('x-guanlian ul .line_4:not(:first)').each((index, item) => {
  //   $(item).text(unescape($(item).text()))
  // })
})
const gID = location.href.match(/\/id\/(\d+)/)[1]
if (Number(gID) === Infinity) {
  throw new Error(`获取产品id失败，id值为${gID}`)
}
const templ = `
  <div style='width:100%;margin:0 auto;text-align:center;'>
    <select name="choseDalei" id="popup_choseDalei" form='not_submit'
    style='margin: 0 auto;width: 35rem;height: 2.5rem;line-height: 2.5rem;display: block;margin-top:1rem;'>
      <option value="false">请等待网络加载</option>
    </select>
    <select name="choseXiaolei" id="popup_choseXiaolei" form='not_submit'
    style='margin: 0 auto;width: 35rem;height: 2.5rem;line-height: 2.5rem;display: block;margin-top:1rem;'>
      <option value="false">请选择大类</option>
    </select>
    <div style='margin: 0 auto;width: 35rem;line-height: 2.5rem;display: block;margin-top:1rem;'>
      <select name="choseXiaoming" id="popup_choseXiaoming" form='not_submit' style='width:100%;'>
        <option value="false">请选择小类</option>
      </select>
    </div>
  </div>
  <div id='popup_confirm' style='display:none;width:7rem;margin:auto;background:#007cb8;color:#fff;text-align: center;margin-top: 1rem;line-height: 2.5rem;cursor: pointer;'>确认提交</div>
`.trim()
function addNewGuanlian (evt) {
  let frameID = layer.open({
    type: 1,
    area: ['700px', '450px'],
    title: '选择关联产品',
    shadeClose: true,
    content: `${templ}`
  })
  if (String(typeof frameID).toLowerCase() === 'number' && frameID > 0) {
    let optionListDalei = ``
    $.ajax(String($('#post_ajax_get_dalei').val()), {
      method: 'post',
      data: {data: 'test'}
    }).fail((err) => {
      alert(`网络连接失败，请检查网络`)
      throw err
    }).done((data) => {
      if (String(data.code) === '1') {
        $.each(data.data, (index, item) => {
          optionListDalei += `<option value="${item.id}">${item.name}</option>`
        })
      } else {
        alert(`服务器响应错误，返回：${data.message}`)
        throw new Error(`服务器响应错误，返回：${data.message}`)
      }
    }).done((data) => {
      console.log(optionListDalei)
      $('#popup_choseDalei').empty().append(optionListDalei)
      $('#popup_choseDalei').val(null)
    })
    $('#popup_choseDalei').on('change', (evt) => {
      $('#popup_choseXiaolei').val(null)
      $('#popup_choseXiaolei').empty().append(`<option value="false">正在加载请稍候</option>`)
      $('#popup_choseXiaoming').val(null)
      $('#popup_choseXiaoming').empty().append(`<option value="false">请选择小类</option>`)
      let xiaoleiOptionList = Promise.resolve($(evt.target).val())
      xiaoleiOptionList.then((value) => Getxiaolei(value))
        .then((value) => {
          console.log(value)
          $('#popup_choseXiaolei').empty().append(String(value))
          $('#popup_choseXiaolei').val(null)
        })
    })
    $('#popup_choseXiaolei').on('change', (evt) => {
      $('#popup_choseXiaoming').val(null)
      $('#popup_choseXiaoming').empty().append(`<option value="false">正在加载请稍候</option>`)
      let xiaomingOptionList = Promise.resolve($(evt.target).val())
      xiaomingOptionList.then((value) => Getxiaoming(value))
        .then((value) => {
          console.log(value)
          $('#popup_choseXiaoming option').remove()
          $('#popup_choseXiaoming').select2({
            data: value
          }).val(null).trigger('change')
        })
    })
    $('#popup_choseXiaoming').on('change', (evt) => {
      if ($('#popup_choseXiaoming').val() !== null && $('#popup_choseXiaoming').val() !== '' && $('#popup_choseXiaoming').val().length > 0) {
        $('#popup_confirm').css('display', 'block')
        $('#popup_confirm').off('click')
        $('#popup_confirm').one({click: writeBackGuanlian}, {})
      } else {
        $('#popup_confirm').off('click')
        $('#popup_confirm').css('display', 'none')
      }
    })
    // 新建多选下拉框
    $('#popup_choseXiaoming').select2({
      placeholder: '请选择小名',
      tags: false,
      multiple: true,
      minimumResultsForSearch: Infinity,
      width: 'element',
      closeOnSelect: false
    }).val(null).trigger('change')
  }
}
function Getxiaolei (fID) {
  let optionList = ``
  return new Promise((resolve, reject) => {
    $.ajax(String($('#post_ajax_get_cpclass').val()), {
      method: 'post',
      data: {f_id: fID}
    }).fail((err) => {
      alert(`获取小类列表失败，请检查网络`)
      $('#popup_choseDalei').val('')
      reject(err)
      throw err
    }).done((data) => {
      if (String(data.code) === '1') {
        $.each(data.data, (index, item) => {
          optionList += `<option value="${item.id}">${item.name}</option>`
        })
        console.log(optionList)
        resolve(optionList)
      } else {
        alert(`服务器响应异常：${data.message}`)
        reject(new Error(`服务器响应异常：${data.message}`))
        throw new Error(`服务器响应异常：${data.message}`)
      }
    })
  })
}
function Getxiaoming (cpTemp) {
  let optionList = ``
  return new Promise((resolve, reject) => {
    $.ajax(String($('#post_ajax_get_litter_name').val()), {
      method: 'post',
      data: {cp_temp: cpTemp}
    }).fail((err) => {
      alert(`获取小名列表失败，请检查网络`)
      $('#popup_choseXiaolei').val(null)
      reject(err)
      throw err
    }).done((data) => {
      if (String(data.code) === '1') {
        let dataSource = []
        $.each(data.data, (index, item) => {
          dataSource.push({
            id: item.id,
            text: item.litter_name
          })
        })
        console.log(dataSource)
        resolve(dataSource)
      } else {
        alert(`服务器响应异常：${data.message}`)
        reject(new Error(`服务器响应异常：${data.message}`))
        throw new Error(`服务器响应异常：${data.message}`)
      }
    })
  })
}

function modifyThisLine (evt) {
  const value = $(evt.target).closest('ul').find('.line_4').text()
  const heightValue = $(evt.target).closest('ul').find('.line_4').height()
  $(evt.target).closest('ul').find('.line_4').height(heightValue)
  $(evt.target).closest('ul').find('.line_4').text(null).append(`<textarea title='点击空白处保存' style='height:100%;width:100%;'></textarea>`)
  $(evt.target).closest('ul').find('.line_4 textarea').focus().val(value)
  $(evt.target).closest('ul').find('.line_4 textarea').on('blur', (evt) => {
    const text = String($(evt.target).val())
    $(evt.target).closest('ul').find('.line_4').text(text)
  })
}

function writeBackGuanlian (evt) {
  const formValue = {
    daleiid: $('#popup_choseDalei').val(),
    cp_class: $('#popup_choseXiaolei').val(),
    /* 关联理由 */
    link_reason: '',
    /* 关联所属产品 */
    g_id: gID,
    /* 被关联产品 */
    link_g_id: $('#popup_choseXiaoming').val()
  }
  const formTextValue = {
    dalei: $(`#popup_choseDalei option[value='${$('#popup_choseDalei').val()}']`).text(),
    xiaolei: $(`#popup_choseXiaolei option[value='${$('#popup_choseXiaolei').val()}']`).text(),
    // 去重的时候添加
    xiaoming: []
  }
  const uniformValue = {
    daleiid: formValue.daleiid,
    cp_class: formValue.cp_class,
    /* 关联理由 */
    link_reason: formValue.link_reason,
    /* 关联所属产品 */
    g_id: formValue.g_id,
    /* 被关联产品 */
    link_g_id: []
  }
  let hadValue = [``]
  // 构建已有值
  $('x-guanlian .line_3').each((index, item) => {
    if (index === 0) {
      // 表头
      ;
    } else if (index === 1) {
      hadValue = [String($(item).attr('inori-data-id'))]
    } else {
      hadValue.push(String($(item).attr('inori-data-id')))
    }
  })
  if (typeof formValue.link_g_id === 'string') {
    formValue.link_g_id = [`${formValue.link_g_id}`]
  }
  // 比对检验是否重复添加
  $.each(formValue.link_g_id, (index, item) => {
    if (hadValue.indexOf(item) === -1) {
      uniformValue.link_g_id.push(item)
      formTextValue.xiaoming.push($(`#popup_choseXiaoming option[value='${item}']`).text())
    }
  })
  // 去重后数组不为空的时候，post到服务器并在成功后append列表
  if (uniformValue.link_g_id.length > 0) {
    let newGuanlian = ``
    alert(`正在请求数据写入权限，请稍后。`)
    Promise.resolve(uniformValue).then((postData) => {
      let promiseQuery = []
      $.each(postData.link_g_id, (index, item) => {
        let postDataItem = Object.assign({}, postData)
        postDataItem.link_g_id = postDataItem.link_g_id[index]
        promiseQuery.push(ajaxPostGuanlianArray(postDataItem))
      })
      return Promise.all(promiseQuery)
    }).then((rawValue) => {
      // if (typeof rawValue.phpValue === 'string') {
      //   rawValue.phpValue = [rawValue.phpValue]
      // }
      uniformValue.link_g_id = String(uniformValue.link_g_id).split(',')
      $.each(rawValue, (index, item) => {
        newGuanlian += `
        <ul>
          <li class="line_1" inori-data-id='${uniformValue.daleiid}'>${formTextValue.dalei}</li>
          <li class="line_2" inori-data-id='${uniformValue.cp_class}'>${formTextValue.xiaolei}</li>
          <li class="line_3" inori-data-id='${uniformValue.link_g_id[index]}'>${formTextValue.xiaoming[index]}</li>
          <li class="line_4" style='min-height:4rem;'>关联理由</li>
          <li class="line_5"><div class="btn btn_modifiy" style="background-image:url('${$('x-guanlian').attr('btn-img-url')}');">修改关联理由</div></li>
          <li class="line_6"><div class="btn btn_del" onclick='deleThisGuanlianLine(this, event)'>删除</div></li>
          <input type='hidden' class='lineGuanlianID' value='${item.phpValue}'>
        </ul>
        `.trim()
      })
      $('.main_table').append(newGuanlian)
      layer.closeAll()
      // 重新挂一次事件
      $('x-guanlian .btn_modifiy').each((index, item) => {
        $(item).off('click')
        $(item).on({click: modifyThisLine}, {})
      })
    })
  } else {
    alert('您选择添加的关联产品都已存在，请检查列表')
    $('#popup_choseDalei').val(null)
    $('#popup_confirm').one({click: writeBackGuanlian}, {})
    throw new Error('关联产品全部重复')
  }
}
function ajaxPostGuanlianArray (data) {
  const postURL = String($('#post_ajax_add_goods_links').val())
  // data.link_g_id = data.link_g_id.join(',')
  return new Promise((resolve, reject) => {
    $.ajax(postURL, {
      method: 'post',
      data: data
    }).done((res) => {
      if (String(res.code) === '1') {
        resolve({
          formData: data,
          phpValue: res.goods_link_id
        })
      } else {
        reject(new Error(`服务器响应错误： ${data.message}`))
      }
    }).fail((err) => {
      $('#popup_confirm').one({click: writeBackGuanlian}, {})
      reject(err)
    })
  })
}

function deleThisGuanlianLine (_this, event) {
  const ID = $(_this).closest('ul').find('.lineGuanlianID').val()
  const AjaxURL = String($('#post_ajax_del_goods_links').val())
  $.ajax(AjaxURL, {
    method: 'post',
    data: {goods_link_id: ID},
    beforeSend: () => {
      layer.msg(`正在与服务器通信`)
    }
  }).done((data) => {
    if (String(data.code) === '1') {
      layer.closeAll()
      $(_this).closest('ul').remove()
    } else {
      alert(`服务器响应异常：${data.message}`)
      throw new Error(`服务器响应异常：${data.message}`)
    }
  }).fail((err) => {
    console.log(err)
    throw err
  })
}

function submitGuanlian () {
  // const dalei = Array.from($('x-guanlian ul .line_1:not(:first)').map((index, item) => { return $(item).attr('inori-data-id') })).join(',')
  // const xiaolei = Array.from($('x-guanlian ul .line_2:not(:first)').map((index, item) => { return $(item).attr('inori-data-id') })).join(',')
  const xiaoming = Array.from($('x-guanlian ul .line_3:not(:first)').map((index, item) => { return $(item).attr('inori-data-id') })).join(',')
  /* 防止出现逗号妨碍分割，为此需要在显示时手动unescape一次 */
  // const guanlianReason = Array.from($('x-guanlian ul .line_4:not(:first)').map((index, item) => { return escape($(item).text()).toLocaleLowerCase() })).join(',')
  // const guanlianID = Array.from($('x-guanlian ul .lineGuanlianID').map((index, item) => { return $(item).val() })).join(',')
  let formValueArray = []
  $('x-guanlian ul:not(:first)').each((index, item) => {
    formValueArray.push({
      goods_link_id: $(item).find('.lineGuanlianID').val(),
      link_reason: $(item).find('.line_4').text()
    })
  })
  $.ajax(String($('#post_ajax_update_goods_links').val()), {
    method: 'post',
    data: {data: formValueArray},
    beforeSend: () => {
      layer.msg('正在发送关联表格数据', {
        icon: 16,
        shade: 0.01
      })
    }
  }).fail((err) => {
    layer.msg(`发送关联表格数据失败！请重试`)
    throw err
  }).done((res) => {
    layer.closeAll()
    const encodeRes = res
    /* 服务器返回修改数组，0为未修改，1 为修改成功 */
    let flag = true
    $.each(encodeRes.data, (index, item) => {
      if (item !== 1 && item !== 0) {
        flag = false
      }
    })
    if (flag) {
      ;
    } else {
      alert(`服务器响应异常： ${encodeRes.data}`)
      throw new Error(`服务器响应异常： ${encodeRes.data}`)
    }
  })
}
